import { defineConfig, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import os from 'os'

let config:UserConfigExport
const moduleName = process.env['npm_config_project'] // 使用`--project=[module_name]`获取模块名
// 获取本机IP
function getIPAdress() {
	let interfaces = os.networkInterfaces()
	for (let devName in interfaces) {
		let iface = interfaces[devName]||[]
		for (let i = 0; i < iface.length; i++) {
			let alias = iface[i]
			if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
				return alias.address
			}
		}
	}
}
const host = getIPAdress()
if (!moduleName) {
  // 构建父模块
  config = {
    plugins: [vue()],
    resolve: {
      alias: {
        // 为`vite.config.ts`文件所在目录起别名`@`
        '@': resolve(__dirname, 'src'),
      }
    },
  }
} else {
  // 构建子模块
  config = {
    plugins: [vue()],
    root: `./src/modules/${moduleName}`,
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '~': resolve(__dirname, `src/modules/${moduleName}`), // 子模块专用别名
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "$/public/scss/mixin.scss";` // 引入scss全局动态样式
        }
      }
    },
    server: {
			open: true,//启动项目自动弹出浏览器
			hmr: true,//开启热更新
			host: host,
			port: 8082,//启动端口
			proxy: {
				'/api': {
					// target:'https://and.vdus.com',	//实际请求地址
					changeOrigin: true,
					rewrite: (path: string) => path.replace(/^\/api/, '')
				},
			}
		},
    build: {
      minify: 'terser', // 必须启用：terserOptions配置才会有效
			terserOptions: {
			  compress: {
          // 生产环境时移除console.log调试代码
          drop_console:true,
          drop_debugger: true,
			  },
			  output: {
          // 去掉注释内容
          comments: true,
			  },
			},
      // https://cn.vitejs.dev/guide/build.html
      rollupOptions: {
        input: resolve(__dirname, `src/modules/${moduleName}/index.html`), // 指定子模块入口文件
        output: {
          dir: `dist/modules/${moduleName}`
        }
      }
    }
  }
}

// https://vitejs.dev/config/
export default defineConfig(config)